﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SuperMap.Data;
using desktop = SuperMap.Desktop;
using SuperMap.Mapping;
using SuperMap.Desktop.UI;
using System.IO;

namespace SuperMap.HB.ThemeWork
{
    public partial class RiverPointControl : UserControl
    {
        private Datasource m_DataSource = desktop.Application.ActiveApplication.Workspace.Datasources["河流数据"];
        private DataSet m_WaterDataset;
        private string m_WaterSheet = "";
        private string m_WaterDatasetName = "";


        public RiverPointControl()
        {
            InitializeComponent();

            groupBox1.Paint += groupBox_Paint;
            groupBox2.Paint += groupBox_Paint;
        }

        private void RiverPointControl_Load(object sender, EventArgs e)
        {
            try
            {
                MessageTip tip = new MessageTip();
                tip.ShowTip();

                cmb_SelectMap.Items.Clear();
                foreach (string name in desktop.Application.ActiveApplication.Workspace.Maps)
                {
                    cmb_SelectMap.Items.Add(name);
                }
                if (cmb_SelectMap.Items.Count > 0)
                {
                    cmb_SelectMap.SelectedIndex = 0;
                    rdo_Select.Enabled = true;
                    rdo_Create.Enabled = true;
                    groupBox1.Enabled = false;
                    groupBox2.Enabled = true;
                }
                else
                {
                    rdo_Select.Enabled = false;
                    rdo_Create.Enabled = false;
                    groupBox1.Enabled = false;
                    groupBox2.Enabled = false;
                }

                cmb_SelectPoint.Items.Clear();
                cmb_SelectPointDataset.Items.Clear();
                foreach (Dataset data in m_DataSource.Datasets)
                {
                    //加载导入的断面数据
                    if (data.Type == DatasetType.Tabular)
                    {
                        cmb_SelectPoint.Items.Add(data.Name);
                    }

                    //加载转换好的断面点数据
                    if (data.Type == DatasetType.Point)
                    {
                        cmb_SelectPointDataset.Items.Add(data.Name);
                    }
                }
                if (cmb_SelectPoint.Items.Count > 0)
                {
                    cmb_SelectPoint.SelectedIndex = 0;
                    btn_ChangerDataType.Enabled = true;
                }
                else
                {
                    btn_ChangerDataType.Enabled = false;
                }
                if (cmb_SelectPointDataset.Items.Count > 0)
                {
                    cmb_SelectPointDataset.SelectedIndex = 0;
                    btn_OK.Enabled = true;
                }
                else
                {
                    btn_OK.Enabled = false;
                }

                tip.HideTip();
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void groupBox_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                GroupBox gBox = (GroupBox)sender;

                e.Graphics.Clear(gBox.BackColor);
                e.Graphics.DrawString(gBox.Text, gBox.Font, Brushes.Black, 10, 1);
                var vSize = e.Graphics.MeasureString(gBox.Text, gBox.Font);
                e.Graphics.DrawLine(Pens.Black, 1, vSize.Height / 2, 8, vSize.Height / 2);
                e.Graphics.DrawLine(Pens.Black, vSize.Width + 8, vSize.Height / 2, gBox.Width - 2, vSize.Height / 2);
                e.Graphics.DrawLine(Pens.Black, 1, vSize.Height / 2, 1, gBox.Height - 2);
                e.Graphics.DrawLine(Pens.Black, 1, gBox.Height - 2, gBox.Width - 2, gBox.Height - 2);
                e.Graphics.DrawLine(Pens.Black, gBox.Width - 2, vSize.Height / 2, gBox.Width - 2, gBox.Height - 2);
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void rdo_Select_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                switch ((sender as RadioButton).Name)
                {
                    case "rdo_Select":
                        groupBox1.Enabled = false;
                        groupBox2.Enabled = true;
                        break;
                    case "rdo_Create":
                        groupBox1.Enabled = true;
                        groupBox2.Enabled = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void chk_EnableLabel_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                cmb_LabelField.Enabled = chk_EnableLabel.Checked;
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_SelectPoint_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //cmb_Lon.Items.Clear();
                //cmb_Lat.Items.Clear();
                //if (m_DataSource.Datasets[cmb_SelectPoint.Text.Trim()] is DatasetVector objDtv)
                //{
                //    foreach (FieldInfo field in objDtv.FieldInfos)
                //    {
                //        if (!field.Name.ToLower().Contains("sm"))
                //        {
                //            cmb_Lon.Items.Add(field.Name);
                //            cmb_Lat.Items.Add(field.Name);
                //        }
                //    }
                //}
                //if (cmb_Lon.Items.Count > 0)
                //{
                //    cmb_Lon.SelectedIndex = 0;
                //}
                //if (cmb_Lat.Items.Count > 0)
                //{
                //    cmb_Lat.SelectedIndex = 0;
                //}
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_SelectPointDataset_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                cmb_ThemeField.Items.Clear();
                cmb_LabelField.Items.Clear();
                if (m_DataSource.Datasets[cmb_SelectPointDataset.Text.Trim()] is DatasetVector objDtv)
                {
                    foreach (FieldInfo field in objDtv.FieldInfos)
                    {
                        if (!field.Name.ToLower().Contains("sm"))
                        {
                            cmb_ThemeField.Items.Add(field.Name);
                            cmb_LabelField.Items.Add(field.Name);
                        }
                    }
                }
                if (cmb_ThemeField.Items.Count > 0)
                {
                    cmb_ThemeField.SelectedIndex = 0;
                }
                if (cmb_LabelField.Items.Count > 0)
                {
                    cmb_LabelField.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void btn_ChangerDataType_Click(object sender, EventArgs e)
        {
            Recordset objRt = null;
            Recordset objRtPoint = null;
            try
            {
                MessageTip tip = new MessageTip();
                tip.ShowTip();

                objRt = (m_DataSource.Datasets[cmb_SelectSheet.Text.Trim()] as DatasetVector).GetRecordset(false, CursorType.Static);
                DatasetVectorInfo info = new DatasetVectorInfo
                {
                    Type = DatasetType.Point,
                    Name = m_DataSource.Datasets.GetAvailableDatasetName(cmb_SelectSheet.Text.Trim() + "_断面点")
                };
                DatasetVector objDtvPoint = m_DataSource.Datasets.Create(info);
                objDtvPoint.PrjCoordSys = m_DataSource.PrjCoordSys;

                List<string> fieldnames = new List<string>();
                foreach (FieldInfo field in objRt.GetFieldInfos())
                {
                    if (!field.Name.ToLower().Contains("sm"))
                    {
                        fieldnames.Add(field.Name);
                        objDtvPoint.FieldInfos.Add(field);
                    }
                }

                objRtPoint = objDtvPoint.GetRecordset(true, CursorType.Dynamic);

                objRt.MoveFirst();
                while (!objRt.IsEOF)
                {
                    double x = double.NaN;
                    double y = double.NaN;
                    if (objRt.GetFieldValue(cmb_Lon.Text.Trim()) != null && !string.IsNullOrEmpty(Convert.ToString(objRt.GetFieldValue(cmb_Lon.Text.Trim()))))
                    {
                        x = Convert.ToDouble(objRt.GetFieldValue(cmb_Lon.Text.Trim()));
                    }
                    if (objRt.GetFieldValue(cmb_Lat.Text.Trim()) != null && !string.IsNullOrEmpty(Convert.ToString(objRt.GetFieldValue(cmb_Lon.Text.Trim()))))
                    {
                        y = Convert.ToDouble(objRt.GetFieldValue(cmb_Lat.Text.Trim()));
                    }
                    if(x != double.NaN && y != double.NaN)
                    {
                        GeoPoint point = new GeoPoint(x, y);

                        Dictionary<string, object> dic = new Dictionary<string, object>();

                        foreach (FieldInfo field in objRt.GetFieldInfos())
                        {
                            if (!field.Name.ToLower().Contains("sm"))
                            {
                                object value = objRt.GetFieldValue(field.Name);
                                dic.Add(field.Name, value);
                            }
                        }

                        bool b = objRtPoint.AddNew(point, dic);
                        bool bb = objRtPoint.Update();
                    }

                    objRt.MoveNext();
                }

                //切换到选择数据组
                rdo_Select.Checked = true;
                groupBox1.Enabled = false;
                groupBox2.Enabled = true;
                cmb_SelectPointDataset.Items.Add(objDtvPoint.Name);
                cmb_SelectPointDataset.SelectedIndex = 0;
                btn_OK.Enabled = true;

                tip.HideTip();
                desktop.Application.ActiveApplication.MessageBox.Show("转换成功！");
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
            finally
            {
                objRt?.Close();
                objRt?.Dispose();
                objRtPoint?.Close();
                objRtPoint?.Dispose();
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            Recordset objRt = null;

            try
            {
                MessageTip tip = new MessageTip();
                tip.ShowTip();

                ThemeUnique themeUnique = new ThemeUnique
                {
                    UniqueExpression = cmb_ThemeField.Text.Trim(),
                    IsDefaultStyleVisible = false
                };

                List<string> lstValues = new List<string>();

                objRt = (m_DataSource.Datasets[cmb_SelectPointDataset.Text.Trim()] as DatasetVector).GetRecordset(false, CursorType.Static);
                objRt.MoveFirst();
                while (!objRt.IsEOF)
                {
                    if (objRt.GetFieldValue(cmb_ThemeField.Text.Trim()) != null)
                    {
                        string value = Convert.ToString(objRt.GetFieldValue(cmb_ThemeField.Text.Trim()));
                        List<string> lstexist = lstValues.FindAll(delegate (string s) { return s.Equals(value); });
                        if (lstexist.Count == 0)
                        {
                            lstValues.Add(value);
                        }
                    }

                    objRt.MoveNext();
                }

                ColorScheme colorScheme = new ColorScheme();
                string xml = "";
                string line = "";
                StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.Length - 4) + @"Templates\ColorScheme\Default\Map_ThemeUnique\LE_Draw.scs");
                while ((line = sr.ReadLine()) != null)
                {
                    xml += line;
                }
                colorScheme.FromXML(xml);

                for (int i = 0; i < lstValues.Count; i++)
                {
                    GeoStyle style = new GeoStyle
                    {
                        LineColor = colorScheme.KeyColors[i],
                        MarkerSize = new Size2D(5, 5)
                    };
                    ThemeUniqueItem item = new ThemeUniqueItem
                    {
                        Unique = lstValues[i],
                        Caption = lstValues[i],
                        Style = style
                    };
                    themeUnique.Add(item);
                }

                desktop.Application.ActiveApplication.MainForm.FormManager.CloseAll(false);
                Map map = desktop.Application.ActiveApplication.CreateMapWindow().MapControl.Map;
                map.Open(cmb_SelectMap.Text);
                DatasetVector dtv = m_DataSource.Datasets[cmb_SelectPointDataset.Text.Trim()] as DatasetVector;
                map.Layers.Add(dtv, themeUnique, true);

                if (chk_EnableLabel.Checked)
                {
                    TextStyle labelStyle = new TextStyle
                    {
                        ForeColor = Color.Black,
                        IsSizeFixed = true,
                        FontHeight = 4.25,
                        FontName = "Microsoft YaHei UI"
                    };
                    ThemeLabel themeLabel = new ThemeLabel
                    {
                        LabelExpression = cmb_LabelField.Text.Trim(),
                        UniformStyle = labelStyle
                    };
                    map.Layers.Add(dtv, themeLabel, true);
                }

                bool exist = false;
                foreach (string mapname in desktop.Application.ActiveApplication.Workspace.Maps)
                {
                    if (mapname.Equals(cmb_SelectMap.Text.Trim()))
                    {
                        exist = true;
                        break;
                    }
                }
                if (exist)
                {
                    desktop.Application.ActiveApplication.Workspace.Maps.SetMapXML(cmb_SelectMap.Text.Trim(), map.ToXML());
                }
                else
                {
                    desktop.Application.ActiveApplication.Workspace.Maps.Add(cmb_SelectMap.Text.Trim(), map.ToXML());
                }
                if (desktop.Application.ActiveApplication.Workspace.Save())
                {
                    tip.HideTip();
                    desktop.Application.ActiveApplication.MessageBox.Show("保存成功！");
                }
                else
                {
                    tip.HideTip();
                    desktop.Application.ActiveApplication.MessageBox.Show("保存失败！");
                }

                tip.HideTip();
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
            finally
            {
                objRt?.Close();
                objRt?.Dispose();
            }
        }

        private void btn_SelectWaterQFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog
                {
                    Filter = "所有文件|*.*|Shapefile文件|*.shp|Excel文件|*.xlsx|Excel文件|*.xls",
                    Multiselect = false
                };
                if (open.ShowDialog() == DialogResult.OK)
                {
                    txt_WaterQPath.Text = open.FileName;
                    ExcelHelper excel = new ExcelHelper();
                    m_WaterDataset = excel.FromFile(open.FileName);
                    if (CheckData.ConfirmData(m_WaterDataset))
                    {
                        cmb_SelectSheet.Items.Clear();
                        foreach (DataTable table in m_WaterDataset.Tables)
                        {
                            cmb_SelectSheet.Items.Add(table.TableName);
                        }
                        if (cmb_SelectSheet.Items.Count > 0)
                        {
                            cmb_SelectSheet.SelectedIndex = 0;
                        }
                    }
                    else
                    {
                        Desktop.Application.ActiveApplication.MessageBox.Show("数据表结构不适用，请修正数据后重试！");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void btn_Import_Click(object sender, EventArgs e)
        {
            try
            {
                MessageTip tip = new MessageTip();
                tip.ShowTip();
                foreach (DataTable table in m_WaterDataset.Tables)
                {
                    if (!table.TableName.Equals(m_WaterSheet))
                    {
                        continue;
                    }
                    DatasetVectorInfo info = new DatasetVectorInfo
                    {
                        Type = DatasetType.Tabular,
                        Name = m_DataSource.Datasets.GetAvailableDatasetName(m_WaterSheet),
                    };
                    m_WaterDatasetName = info.Name;
                    DatasetVector objDtV = m_DataSource.Datasets.Create(info);
                    objDtV.Open();

                    List<FieldInfo> lstColumns = new List<FieldInfo>();
                    cmb_Lon.Items.Clear();
                    cmb_Lat.Items.Clear();
                    foreach (DataColumn column in table.Columns)
                    {
                        if (column.ColumnName.ToLower().Contains("sm"))
                        {
                            continue;
                        }
                        FieldInfo fieldInfo = new FieldInfo { Name = column.ColumnName, Caption = column.ColumnName, Type = FieldType.Text };
                        objDtV.FieldInfos.Add(fieldInfo);
                        lstColumns.Add(fieldInfo);
                        cmb_Lon.Items.Add(fieldInfo.Name);
                        cmb_Lat.Items.Add(fieldInfo.Name);
                    }
                    if (cmb_Lon.Items.Count > 0)
                    {
                        cmb_Lon.SelectedIndex = 0;
                    }
                    if (cmb_Lat.Items.Count > 0)
                    {
                        cmb_Lat.SelectedIndex = 0;
                    }

                    Recordset objRt = null;

                    try
                    {
                        objRt = objDtV.GetRecordset(true, CursorType.Dynamic);

                        Recordset.BatchEditor editor = objRt.Batch;
                        editor.MaxRecordCount = 50;
                        editor.Begin();

                        foreach (DataRow row in table.Rows)
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            foreach (FieldInfo fieldInfo in lstColumns)
                            {
                                dic.Add(fieldInfo.Name, row[fieldInfo.Name]);
                            }
                            objRt.AddNew(null, dic);
                        }

                        editor.Update();

                    }
                    catch (Exception ex)
                    {
                        Log.OutputBox(ex);
                    }
                    finally
                    {
                        objRt?.Close();
                        objRt?.Dispose();
                    }
                }

                tip.HideTip();
                Desktop.Application.ActiveApplication.MessageBox.Show("导入成功！");
                btn_ChangerDataType.Enabled = true;
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_SelectSheet_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                m_WaterSheet = cmb_SelectSheet.Text;
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }
    }
}
